import { getCss, removeUnit, setCss } from '@/utils/DomUtil';
import EasingUtil from './EasingUtil';

export function animate(
  el: HTMLElement,
  target: GObject,
  duration: number,
  callback?: () => void,
  easing?: 'linear' | 'easeInQuad' | 'easeOutQuad' | 'easeInOutQuad',
) {
  const start: GObject = {};
  const delta: GObject = {};

  for (let key in target) {
    start[key] = getCss(el, key);
    delta[key] = removeUnit(target[key]) - start[key];
  }

  let startTime = Date.now();
  const timer = setInterval(() => {
    let time = Date.now() - startTime;
    if (time >= duration) {
      clearInterval(timer);
      for (let key in target) {
        setCss(el, key, target[key]);
      }

      callback && callback.call(el);
      return;
    }

    for (let key in target) {
      let current = EasingUtil[easing ?? 'linear'](
        time,
        start[key],
        delta[key],
        duration,
      );
      setCss(el, key, current);
    }
  }, 20);
}
